const { db, query } = require("../../db/index")
const { decrypt } = require("../../utils/crypt_util")
const { generateKeyPair } = require('../../utils/encrypt_util')

const login = async (req, res) => {
    const { sessionid } = req.body;

    if (!sessionid) {
        return res.status(400).send({ error: 'sessionid is required' });
    }

    try {
        if (sessionid.length != 32) {
            return res.status(400).send({ error: 'the sessionid format is invalid' });
        }

        const result = await query("SELECT * FROM session_user WHERE ?", { session_id: sessionid })
        if (result && result.length > 0) {
            const obj = JSON.parse(JSON.stringify(result));
            res.send({ sessionid: sessionid, publicKey: obj[0].public_key });
            return
        }

        var keyPair = generateKeyPair();
        let insertRes = await query("INSERT INTO session_user SET ?", { session_id: sessionid, public_key: keyPair[0], private_key: keyPair[1] });

        if (!insertRes) {
            return res.status(500).send({ error: 'Failed to login' });
        }

        res.send({ sessionid: sessionid, publicKey: keyPair[0] });
    } catch (error) {
        console.error('Error login:', error);
        res.status(500).send({ error: 'Failed to login' });
    }

}

exports.login = login